﻿using System;
using System.Reflection;

using SBPweb.RIA.Shared.Contracts.Extensibility;

using SBPweb.RIA.Shared.Contracts.Controllers;
using SBPweb.RIA.Shared.Contracts.Models;

namespace SBPweb.RIA.Client.Contracts.Base
{

    public abstract class ControllerBase<TModelContract, TModel, TController> : IController<TModelContract>
        where TModelContract : IModel
        where TModel : IModel
        where TController : IController<TModelContract>
    {

        #region Fields
        
        private static Type ControllerType = typeof(TController);

        #endregion

        #region Constructor logic

        public ControllerBase()
        {
        }

        #endregion

        #region Property accessors

        public static IExtendableApplication Application
        {
            get
            {
                return System.Windows.Application.Current as IExtendableApplication;
            }
        }

        public virtual TModelContract Model
        {
            get;
            protected set;
        }

        public static TController Controller
        {
            get
            {
                return FetchController();
            }
        }

        #endregion

        #region Events
        
        #endregion

        #region Methods

        protected static void RegisterController(TController controller)
        {
            string key = ControllerType.FullName;
            RegisterController(key, controller);
#if !WINDOWS_PHONE
            Application.Settings.IgnoreDuringPersistency(key);
#endif
        }

        protected static void RegisterController(string key, TController controller)
        {
            if (Application == null)
            {
                return;
            }
            Application.Put<TController>(key, controller);
        }

        protected static TController FetchController()
        {
            return FetchController(ControllerType.FullName);
        }

        protected static TController FetchController(string key)
        {
            if (Application == null)
            {
                return default(TController);
            }
            return Application.Get<TController>(key);
        }

        #endregion

    }

}